package edu.hawaii.myisern.model;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

/**
 * Handler to send log output to standard output.
 * 
 * @author Randy Cox
 */
public class LogHandler extends Handler {

  /** Since this handler just prints to standard output, nothing to close. */
  public void close() {
    // Empty
  }

  /** Nothing the flush. */
  public void flush() {
    // Empty
  }

  /**
   * Sends output to standard out.
   * 
   * @param record LogRecord to format and print.
   */
  public void publish(LogRecord record) {
    this.flush();

    // Format message.
    Long msec = record.getMillis();
    Date date = new Date();
    date.setTime(msec);
    String message = date.toString();
    message = message.concat(": " + record.getLevel().toString() + " " + record.getMessage()
        + "\r\n");

    // Open log file for appending.
    /** Log file to write too. */
    File logFile = new File(Log.LOG_FILENAME);
    FileWriter fileWriter = null;
    try {
      fileWriter = new FileWriter(logFile, true);
      fileWriter.write(message);
      fileWriter.flush();
      fileWriter.close();
    }
    catch (IOException e) {
      System.err.println("Log StandardHander.publish(): I/O error with log file:"
          + Log.LOG_FILENAME);
    }

    // Print out message to standard out if flag set.
    if (Log.verbose) {
      System.out.print(message);
      System.out.flush();
    }
  }
}
